package com.heba.gcglobal.app.jpush
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import cn.jpush.android.api.JPushInterface
import com.atom.eamoving.app.ui.activity.main.MainActivity
import org.json.JSONException
import org.json.JSONObject

class KTMyReceiver: BroadcastReceiver() {
    override fun onReceive(p0: Context?, p1: Intent?) {
        val bundle = p1!!.extras
        Log.d("JPUSHDEBUG", "action:"+p1.action)
        when(p1.action) {
            JPushInterface.ACTION_CONNECTION_CHANGE -> { //连接
                val connected = p1.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false)
                Log.d("JPUSHDEBUG", connected.toString())
            }
            JPushInterface.ACTION_MESSAGE_RECEIVED -> { //收到自定义消息
                processCustomMessage(p0!!, bundle!!)
            }
            JPushInterface.ACTION_NOTIFICATION_RECEIVED -> { //收到通知栏消息
                val notifactionId = bundle!!.getInt(JPushInterface.EXTRA_NOTIFICATION_ID)
                Log.d("JPUSHDEBUG", "received notice:"+notifactionId.toString())
            }
            JPushInterface.ACTION_NOTIFICATION_OPENED -> { //用户点开通知栏消息
                Log.d("JPUSHDEBUG", "OPENED")
            }
        }
    }

    private fun processCustomMessage(context: Context, bundle: Bundle) {
        if (MainActivity.isForeground) {
            val msg = bundle.getString(JPushInterface.EXTRA_MESSAGE)
            val extras = bundle.getString(JPushInterface.EXTRA_EXTRA)
            val intent = Intent(JPushInterface.ACTION_MESSAGE_RECEIVED)
            intent.putExtra("message", msg)
            if (!isEmpty(extras)) {
                try {
                    val extraJson = JSONObject(extras)
                    if (extraJson.length() > 0) {
                        intent.putExtra("extras", extras)
                    }
                } catch (e: JSONException) {

                }
            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
        }
    }

    fun isEmpty(str: String?): Boolean {
        if (null == str)
            return true
        if (str.length == 0)
            return true
        if (str.trim().length == 0)
            return true
        return false
    }
}